<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=0, viewport-fit=cover" />
	<title>chain</title>
</head>
<body>
<script>
// 同步任务[ sleep eat sleepFirst eat]
// 异步微任务[]
// 异步宏任务[setTimeout]
function Person(name) {
	if (!(this instanceof Person)) {
		return new Person(name);
	}
	this.name = name;
	this.tasks = [];

	this.init();

	setTimeout(async () => {
		for (fn of this.tasks) {
			await fn();
		}
	})
}

Person.prototype.init = function () {
	this.tasks.push(() => {
		console.log(`自我介绍: 我是${ this.name }`)
	})
	return this;
};
Person.prototype.sleep = function (wait) {
	this.tasks.push(() => {
		console.log(`我再歇${ wait }ms`)
		return new Promise(resolve => {
			setTimeout(() => {
				resolve();
			}, wait)
		})
	})
	return this;
};
Person.prototype.eat = function (thing) {
	this.tasks.push(() => {
		console.log(`正在吃${ thing }`)
	});
	return this;
};
// 优先!
Person.prototype.sleepFirst = function (wait) {
	this.tasks.unshift(() => {
		console.log(`先睡觉${ wait }ms`)
		return new Promise(resolve => {
			setTimeout(() => {
				resolve();
			}, wait)
		})
	});
	return this;
};

/**
 * 题目: 控制台打印出如下结果
 * 先睡觉3000ms 卡住
 * 自我介绍: 我是tom
 * 我再歇2000ms 卡住
 * 正在吃饭
 * 正在吃水果
 */
const p = Person('tom') // 自我介绍: 我是tom
	.sleep(2000) // 我再歇2000ms 卡住
	.eat('饭') // 正在吃饭
	.sleepFirst(3000) // 最先执行 先睡觉3000ms 卡住
	.eat('水果') // 正在吃水果

// console.log(`p-------`, p)
</script>
</body>
</html>
